package smashedapples.google.financials
{
	import mx.rpc.AsyncToken;
	import mx.rpc.events.ResultEvent;
	import mx.rpc.http.mxml.HTTPService;
	
	import smashedapples.google.consts.GoogleConsts;
	import smashedapples.google.googleapi.BaseGoogleDataApi;
	import smashedapples.google.googleapi.IGoogleDataApi;
	import smashedapples.utils.XmlUtils;
	
	

	public class GoogleFinancialsApi extends BaseGoogleDataApi implements IGoogleDataApi
	{
	
		
		[Bindable] public var portfolios:XML;
		
		[Bindable] public var positions:XML;

		[Bindable] public var selectedPortfolio:XML;
		
		public var $selectedPortfolioIndex:int;
		
		[Bindable]
		public function get selectedPortfolioIndex():int
		{
			return $selectedPortfolioIndex;
		}
		
		public function set selectedPortfolioIndex( value:int ):void
		{	
			if( this.selectedPortfolioIndex == value )
				return;
				
			$selectedPortfolioIndex = value;
			this.addPropertyChanged( "selectedPortfolioIndex" );
		}
		
		public function onCommitSelectedPortfolioIndex():void
		{
			if( !isNaN(this.selectedPortfolioIndex) && this.selectedPortfolioIndex != -1)
				this.getPositions( this.selectedPortfolioIndex );
		}
		
		
		public function GoogleFinancialsApi():void
		{
			this.service = GoogleConsts.FINANCIAL_DATA_API_SOURCE;
			
			this.addEventListener( "authenticated", handleAuthentication );
		}
		
		private function handleAuthentication( event:AppEvent ):void
		{
			if( this.isAuthenticated() )
				this.getPortfolios();
		}


		public function getPortfolios():AsyncToken
		{
			var service:HTTPService = this.getHttpService( GoogleConsts.FINANCIALS_PORTFOLIOS_URL, handleGetPortfoliosResult )
				service.resultFormat = "e4x";
			return	service.send();
		}
		
		
		private function handleGetPortfoliosResult( event:ResultEvent ):void
		{
			this.portfolios = XmlUtils.removeDefaultNamespace( new XML(event.result) );
			
			
			trace( this.portfolios.toXMLString() );
		}
		
		public function getPositions( position:int ):AsyncToken
		{
			var url:String = GoogleConsts.FINANCIALS_POSITIONS_URL( position + 1 );
			var service:HTTPService = this.getHttpService( url, handleGetPositionsResult )
				service.resultFormat = "e4x";
			return	service.send();
		}
		
		
		private function handleGetPositionsResult( event:ResultEvent ):void
		{
			this.positions = XmlUtils.removeDefaultNamespace( new XML(event.result) );
			
			
			trace( this.positions.toXMLString() );
		}
		
		
	}
}